const axios = require('axios');
const FormData = require('form-data');
//const $ = new Env("人民出行V1");
//cron 14 7 * * * 

// 公共配置参数
const commonParams = {
    adCode: '440500',
    appFrom: '15',
    deviceType: '2',
    mobileLatitude: '23.39385145',
    mobileLongitude: '116.73041097',
    appVersion: '7.1.8',
    userId: '26501181',
    token: '1GDKu9Lxciqh6DKM'
};

// 公共请求头
const commonHeaders = {
    'User-Agent': 'Mozilla/5.0 (Linux; Android 14; 23127PN0CC Build/UKQ1.230804.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/134.0.6998.136 Mobile Safari/537.36 XWEB/1340153 MMWEBSDK/20221011 MMWEBID/9222 MicroMessenger/8.0.30.2260(0x28001E3B) WeChat/arm64 Weixin NetType/4G Language/zh_CN ABI/arm64 miniProgram/wxec491985214cc7fc',
    'Accept': 'application/json, text/plain, */*',
    'Accept-Encoding': 'gzip, deflate, br, zstd',
    'sec-ch-ua-platform': '"Android"',
    'sec-ch-ua': '"Chromium";v="134", "Not:A-Brand";v="24", "Android WebView";v="134"',
    'sec-ch-ua-mobile': '?1',
    'Origin': 'https://static.meboth.cn',
    'X-Requested-With': 'com.tencent.mm',
    'Sec-Fetch-Site': 'cross-site',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Dest': 'empty',
    'Referer': 'https://static.meboth.cn/',
    'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7'
};

// 动态导入通知模块
let sendNotify;
try {
    sendNotify = require('./sendNotify.js');
    console.log('通知模块加载成功');
} catch (e) {
    console.log('通知模块加载失败，将不会发送通知', e.message);
    sendNotify = {
        sendNotify: (title, content) => {
            console.log(`[模拟通知] ${title} => ${content}`);
        }
    };
}

// 创建综合通知内容
let combinedResults = {
    signResult: null,
    miniProgramSignResult: null,
    drawResult: null,
    errors: []
};

// 获取当前时间
const getCurrentTime = () => {
    return new Date().toLocaleString('zh-CN', { 
        year: 'numeric', 
        month: '2-digit', 
        day: '2-digit', 
        hour: '2-digit', 
        minute: '2-digit', 
        second: '2-digit',
        hour12: false
    });
};

// 格式化综合通知内容
const formatNotification = () => {
    let content = `⏰ 执行时间: ${getCurrentTime()}\n\n`;
    
    content += `🔔 社群签到: ${combinedResults.signResult || '无结果'}\n`;
    content += `📱 小程序签到: ${combinedResults.miniProgramSignResult || '无结果'}\n`;
    content += `🎁 抽奖结果: ${combinedResults.drawResult || '无结果'}\n`;
    
    if (combinedResults.errors.length > 0) {
        content += `\n❌ 错误信息:\n`;
        combinedResults.errors.forEach((err, index) => {
            content += `${index + 1}. ${err}\n`;
        });
    }
    
    return content;
};

// 社群签到请求
const makeSignRequest = () => {
    let data = new FormData();
    Object.entries(commonParams).forEach(([key, value]) => {
        data.append(key, value);
    });
    data.append('timestamp', '1753265961617');
    data.append('sign', '16cf72227fa709c344d5b01d048f05c7');

    let config = {
        method: 'POST',
        url: 'https://me.baojia.com/bike/chatSign',
        headers: {
            ...commonHeaders,
            ...data.getHeaders()
        },
        data: data
    };

    return axios.request(config);
};

// 小程序签到请求
const makeMiniProgramSignRequest = () => {
    let data = new FormData();
    Object.entries(commonParams).forEach(([key, value]) => {
        data.append(key, value);
    });
    data.append('timestamp', '1751363614814');
    data.append('sign', '0e0c3252563831a86ababf10485f2984');

    let config = {
        method: 'POST',
        url: 'https://me.baojia.com/bike/activity/sign/data',
        headers: {
            ...commonHeaders,
            ...data.getHeaders()
        },
        data: data
    };

    return axios.request(config);
};

// 抽奖请求
const makeDrawRequest = () => {
    let data = new FormData();
    Object.entries(commonParams).forEach(([key, value]) => {
        data.append(key, value);
    });
    data.append('timestamp', '1753265967184');
    data.append('sign', 'd7b63600f1f42a30c3b6575c08fe10d0');

    let config = {
        method: 'POST',
        url: 'https://me.baojia.com/bike/chatDrawGift',
        headers: {
            ...commonHeaders,
            ...data.getHeaders()
        },
        data: data
    };

    return axios.request(config);
};

// 解析小程序签到结果
const parseMiniProgramSignResult = (response) => {
    if (!response.data) return '签到失败';
    
    const { data, message } = response.data;
    let result = message || '签到成功';
    
    if (data) {
        const signedDay = data.dayList.find(day => day.signStatus === 1);
        if (signedDay) {
            const date = signedDay.curDay.split(' ')[0];
            result += ` (已连续签到 ${data.signedCount}天)`;
        }
    }
    
    return result;
};

// 主执行函数
const main = async () => {
    try {
        // 执行社群签到
        const signResponse = await makeSignRequest();
        combinedResults.signResult = signResponse.data.message || '社群签到成功(无返回消息)';
        console.log('社群签到结果:', combinedResults.signResult);
        
        // 等待5秒
        await new Promise(resolve => setTimeout(resolve, 5000));
        
        // 执行小程序签到
        const miniSignResponse = await makeMiniProgramSignRequest();
        combinedResults.miniProgramSignResult = parseMiniProgramSignResult(miniSignResponse);
        console.log('小程序签到结果:', combinedResults.miniProgramSignResult);
        
        // 等待5秒
        await new Promise(resolve => setTimeout(resolve, 5000));
        
        // 执行抽奖
        const drawResponse = await makeDrawRequest();
        combinedResults.drawResult = drawResponse.data.message || '抽奖成功(无返回消息)';
        console.log('抽奖结果:', combinedResults.drawResult);
    } catch (error) {
        const errorMsg = error.response 
            ? `HTTP ${error.response.status}: ${error.response.data.message || JSON.stringify(error.response.data)}`
            : error.message;
        
        console.error('请求出错:', errorMsg);
        combinedResults.errors.push(errorMsg);
    } finally {
        // 发送综合通知
        const notificationContent = formatNotification();
        sendNotify.sendNotify('人民出行签到综合报告', notificationContent);
        console.log('综合通知已发送:\n', notificationContent);
    }
};

// 启动执行
main();